﻿using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Apps.Excel
{
    /// <summary>
    /// 导出Excel:其实就是要生成一个Excel文件，Excel文件对应的文件流
    /// 导入Excel:读取一个文件,读取文件流,需要从文件流中读取我们需要的各种数据
    /// </summary>
    public class ExcelOperationHelper
    {
        /// <summary>
        /// 创建一个ExcelWorkbook
        /// </summary>
        /// <returns></returns>
        public static IWorkbook CreateExcelWorkbook()
        {
            //HSSFWorkbook:是操作Excel2003以前（包括2003）的版本，扩展名是.xls
            //XSSFWorkbook: 是操作Excel2007的版本，扩展名是.xlsx
            HSSFWorkbook _Workbook = new HSSFWorkbook();
            ISheet sheet = _Workbook.CreateSheet("Sheet1");
            {
                IRow titleRow = sheet.CreateRow(0);
                ICell cell = titleRow.CreateCell(0);
                cell.SetCellValue("姓名");

                ICell cell1 = titleRow.CreateCell(1);
                cell1.SetCellValue("年龄");

                ICell cell12 = titleRow.CreateCell(2);
                cell12.SetCellValue("地址");
            }

            {
                IRow titleRow = sheet.CreateRow(1);
                ICell cell = titleRow.CreateCell(0);
                cell.SetCellValue("张三");

                ICell cell1 = titleRow.CreateCell(1);
                cell1.SetCellValue("18");

                ICell cell12 = titleRow.CreateCell(2);
                cell12.SetCellValue("金华");
            }

            return _Workbook;
        }


        /// <summary>
        /// 导出
        /// </summary>
        public static IWorkbook DataToHSSFWorkbook(List<ExcelDataResource> dataResources)
        {
            //XSSFWorkbook:最多创建1048575行(超出需要分多个sheet创建行)
            //HSSFWorkbook:最多创建65535行(超出需要分多个sheet创建行)
            IWorkbook _workbook = new XSSFWorkbook(); //new HSSFWorkbook();

            //IWorkbook _workbook = new HSSFWorkbook();

            if (dataResources == null || dataResources.Count() == 0)
            {
                return _workbook;
            }

            //每循环一次,就生成一个Sheet页
            foreach (var sheetResource in dataResources)
            {
                if (sheetResource.SheetDataResource != null && sheetResource.SheetDataResource.Count == 0)
                    break;

                //创建页签
                ISheet sheet = _workbook.CreateSheet(sheetResource.SheetName);
                //确定当前这一页多少列---取决保存当前Sheet页数据的实体属性中的标记的特性
                object obj = sheetResource.SheetDataResource![0];

                //获取需要导出的所有列
                Type type = obj.GetType();
                List<PropertyInfo> propList = type.GetProperties().Where(c => c.IsDefined(typeof(TitleAttribute), true)).ToList();


                //确定表头在哪一行生成
                int titleIndex = 0;
                if (sheetResource.TitleIndex >= 0)
                {
                    titleIndex = sheetResource.TitleIndex - 1;
                }
                //基于当前的这个Sheet创建第一行:默认第一行作为表头
                IRow titleRow = sheet.CreateRow(titleIndex);

                //给表头添加样式
                ICellStyle style = _workbook.CreateCellStyle();
                style.FillForegroundColor = HSSFColor.Grey25Percent.Index;
                style.FillPattern = FillPattern.SolidForeground;
                style.FillBackgroundColor = HSSFColor.Automatic.Index;

                style.Alignment = HorizontalAlignment.CenterSelection;
                style.VerticalAlignment = VerticalAlignment.Center;
                titleRow.Height = 100 * 4;

                //给表头行,分别创建单元格,并赋值字段的名称
                for (int i = 0; i < propList.Count; i++)
                {
                    TitleAttribute propertyAttribute = propList[i].GetCustomAttribute<TitleAttribute>()!;
                    if (propertyAttribute == null) continue;

                    ICell cell = titleRow.CreateCell(i);
                    cell.SetCellValue(propertyAttribute.Title);
                    cell.CellStyle = style;
                }

                //去生成数据
                for (int i = 0; i < sheetResource.SheetDataResource.Count(); i++)
                {
                    IRow row = sheet.CreateRow(i + titleIndex + 1);
                    object objInstance = sheetResource.SheetDataResource[i];

                    for (int j = 0; j < propList.Count; j++)
                    {
                        ICell cell = row.CreateCell(j);
                        //因为定义的是object,只能通过反射去取对象里面的值
                        cell.SetCellValue(propList[j].GetValue(objInstance)?.ToString());
                    }

                }
            }

            return _workbook;
        }

        /// <summary>
        /// 生成Excel的内存流-MemoryStream
        /// </summary>
        /// <param name="dataResources"></param>
        /// <returns></returns>
        public static MemoryStream ToExcelMemoryStream(List<ExcelDataResource> dataResources)
        {
            IWorkbook _workbook = DataToHSSFWorkbook(dataResources);
            using (MemoryStream stream = new MemoryStream())
            {
                _workbook.Write(stream);
                return stream;
            }

        }

        /// <summary>
        ///通过数据生成Excel  然后转换成byte[]
        /// </summary>
        /// <param name="dataResources"></param>
        /// <returns></returns>
        public static byte[] ToExcelByteArray(List<ExcelDataResource> dataResources)
        {
            IWorkbook _workbook = DataToHSSFWorkbook(dataResources);
            using (MemoryStream stream = new MemoryStream())
            {
                
                _workbook.Write(stream);
                byte[] bt = stream.ToArray();
                //stream.Write(bt, 0, (int)stream.Length);
                return bt;
            }   
        }

        /// <summary>
        /// Excel转换成DataTable
        /// </summary>
        /// <param name="hssfWorkbook"></param>
        /// <returns></returns>
        public static List<DataTable> ToExcelDataTable(IWorkbook workbook)
        {
            List<DataTable> datatableList = new List<DataTable>();

            for (int sheetIndex = 0; sheetIndex < workbook.NumberOfSheets; sheetIndex++)
            {
                ISheet sheet = workbook.GetSheetAt(sheetIndex);

                //获取表头FirstRowNum 第一行索引0
                IRow header = sheet.GetRow(sheet.FirstRowNum); //获取第一行
                if (header == null)
                    break;

                int startRow = 0;//数据的第一行索引

                DataTable dtNpoi = new DataTable();
                startRow = sheet.FirstRowNum + 1;

                for (int i = header.FirstCellNum; i < header.LastCellNum; i++)
                {
                    ICell cell = header.GetCell(i);
                    if (cell != null)
                    {
                        string cellValue = cell.StringCellValue.Trim();
                        if (cellValue != null)
                        {
                            DataColumn col = new DataColumn(cellValue);
                            dtNpoi.Columns.Add(col);
                        }
                        else
                        {
                            DataColumn col = new DataColumn();
                            dtNpoi.Columns.Add(col);
                        }
                    }
                }

                //数据 LastRowNum 最后一行的索引 如第九行---索引8
                for (int i = startRow; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i); //获取第i行
                    if (row == null)
                    {
                        continue;
                    }

                    DataRow dr = dtNpoi.NewRow();
                    //遍历每行的单元格
                    for (int j = 0; j < row.LastCellNum; j++)
                    {
                        if (row.GetCell(j) != null)
                            dr[j] = row.GetCell(j).StringCellValue;
                    }
                    dtNpoi.Rows.Add(dr);
                }

                datatableList.Add(dtNpoi);

            }

            return datatableList;
        }


        public static List<DataTable> ExcelStramToDataTable(Stream stream)
        {
            IWorkbook workbook = WorkbookFactory.Create(stream);
            return ToExcelDataTable(workbook);
        }

    }
}
